<template>
    <div class="home-content" :class="{ 'no-sidebar': isMobile }" id="report-management-container">
        <el-form :model="searchForm" :inline="true" id="date-search-form">
            <el-form-item label="时间段" id="date-range-form-item">
                <el-date-picker id="date-range-picker" v-model="searchForm.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="dateShortcuts" :default-time="[
                        new Date(2000, 1, 1, 0, 0, 0),
                        new Date(2000, 1, 1, 23, 59, 59)
                    ]" :disabled-date="disabledDate" />
            </el-form-item>
        </el-form>
        <el-form :model="searchForm" :inline="true" class="second-line" id="task-search-form">
            <el-form-item label="任务名称" id="task-name-form-item">
                <el-input id="task-name-input" v-model="searchForm.taskName" placeholder="任务名称" clearable />
            </el-form-item>
            <el-form-item class="button-group" id="search-button-group">
                <el-button id="search-submit-button" type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="charts-container" id="report-charts-container">
            <div class="chart-box" id="weekly-chart-box">
                <div ref="weeklyTaskChart" class="chart" id="weekly-task-chart"></div>
            </div>
            <div class="chart-box" id="status-chart-box">
                <div ref="taskStatusChart" class="chart" id="task-status-chart"></div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useReportManagementStore } from '@/store/reportManagement'
import { storeToRefs } from 'pinia'

const store = useReportManagementStore()
const { taskLineData, taskStatusData, loading, error } = storeToRefs(store)

// 修改 getDateRange 函数
const getDateRange = () => {
    // 设置开始时间为当天的 00:00:00
    const start = new Date()
    start.setHours(0, 0, 0, 0)
    
    // 结束时间就是当前日期加6天（总共7天）
    const end = new Date(start)
    end.setDate(start.getDate() + 6)
    end.setHours(23, 59, 59, 999)
    
    console.log('开始时间:', start.toLocaleString())
    console.log('结束时间:', end.toLocaleString())
    
    return [start, end]
}

// 搜索表单数据
const searchForm = ref({
    dateRange: getDateRange(),  // 现在可以安全调用 getDateRange
    taskName: ''
})

// 日期快捷选项
const dateShortcuts = [
    {
        text: '本周',
        value: () => {
            return getDateRange()
        }
    },
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        }
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        }
    },
    {
        text: '未来一周',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
            return [start, end]
        }
    }
]

// 添加日期禁用配置
const disabledDate = (time) => {
    return false
}

// 图表初始化方法
const initWeeklyTaskChart = () => {
    const chart = echarts.init(weeklyTaskChart.value)
    const option = {
        title: {
            text: '已完成任务趋势'
        },
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                // 在提示框中显示完整日期
                const data = taskLineData.value[params[0].dataIndex]
                return `${data.fullDate}<br/>已完成任务数：${params[0].value}`
            }
        },
        xAxis: {
            type: 'category',
            data: taskLineData.value.map(item => item.date),
            axisLabel: {
                rotate: 30,
                interval: 'auto' // 自动计算显示间隔，避免重叠
            }
        },
        yAxis: {
            type: 'value',
            name: '已完成任务数'
        },
        series: [{
            data: taskLineData.value.map(item => item.value),
            type: 'line',
            smooth: true,
            name: '已完成任务',
            itemStyle: {
                color: '#67C23A'
            },
            lineStyle: {
                color: '#67C23A'
            }
        }]
    }
    chart.setOption(option)
}

const initTaskStatusChart = () => {
    const chart = echarts.init(taskStatusChart.value)
    const option = {
        title: {
            text: '任务状态分布'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        xAxis: {
            type: 'category',
            data: ['进行中', '已完成', '未完成']
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: taskStatusData.value,
            type: 'bar',
            barWidth: '40%',
            itemStyle: {
                color: function (params) {
                    const colors = ['#409EFF', '#67C23A', '#F56C6C'];
                    return colors[params.dataIndex];
                }
            }
        }]
    }
    chart.setOption(option)
}

// 添加图表的ref
const weeklyTaskChart = ref(null)
const taskStatusChart = ref(null)

// 修改查询方法
const handleSearch = async () => {
    const params = {
        title: searchForm.value.taskName || '',
        createTime: '',
        endTime: ''
    }

    // 处理时间范围
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
        // 如果选择了时间范围，使用选择的时间
        const startDate = new Date(searchForm.value.dateRange[0])
        startDate.setHours(0, 0, 0, 0)
        
        const endDate = new Date(searchForm.value.dateRange[1])
        endDate.setHours(23, 59, 59, 999)
        
        params.createTime = startDate.getTime().toString()
        params.endTime = endDate.getTime().toString()
    }

    // 只有在点击查询按钮且所有参数都为空时，才使用默认时间范围
    if (!params.title && !params.createTime && !params.endTime && !searchForm.value.dateRange) {
        // 设置开始时间为当前时间
        const start = new Date()
        start.setHours(0, 0, 0, 0)
        
        // 结束时间为当前时间加6天
        const end = new Date(start)
        end.setDate(start.getDate() + 6)
        end.setHours(23, 59, 59, 999)
        
        params.createTime = start.getTime().toString()
        params.endTime = end.getTime().toString()
    }

    console.log('查询参数:', params)
    await store.fetchReportData(params)
    updateCharts()
}

// 更新图表数据的方法
const updateCharts = () => {
    // 更新周任务完成趋势图
    if (weeklyTaskChart.value) {
        const weeklyChart = echarts.getInstanceByDom(weeklyTaskChart.value)
        if (weeklyChart) {
            weeklyChart.setOption({
                xAxis: {
                    type: 'category',
                    data: taskLineData.value.map(item => item.date)
                },
                series: [{
                    data: taskLineData.value.map(item => item.value),
                    type: 'line',
                    smooth: true
                }]
            })
        }
    }

    // 更新任务状态统计图
    if (taskStatusChart.value) {
        const statusChart = echarts.getInstanceByDom(taskStatusChart.value)
        if (statusChart) {
            statusChart.setOption({
                series: [{
                    data: taskStatusData.value
                }]
            })
        }
    }
}

// 监听数据变
watch([taskLineData, taskStatusData], () => {
    updateCharts()
})

// 监听窗口大小变化，调整图表大小
const handleResize = () => {
    const weeklyChart = echarts.getInstanceByDom(weeklyTaskChart.value)
    const statusChart = echarts.getInstanceByDom(taskStatusChart.value)

    if (weeklyChart) {
        weeklyChart.resize()
        // 更新x轴标签旋转角度
        weeklyChart.setOption({
            xAxis: {
                axisLabel: {
                    rotate: window.innerWidth <= 768 ? 30 : 0
                }
            }
        })
    }

    if (statusChart) {
        statusChart.resize()
        // 更新柱子宽度
        statusChart.setOption({
            series: [{
                barWidth: window.innerWidth <= 768 ? '60%' : '40%'
            }]
        })
    }
}

// 添加移动端检测
const isMobile = ref(false)

const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768
}

// 修改 onMounted
onMounted(() => {
    checkMobile()
    window.addEventListener('resize', checkMobile)

    // 确保 DOM 已经渲染完成后再初始化图表
    nextTick(() => {
        initWeeklyTaskChart()
        initTaskStatusChart()
        // 初始化完成后加载数据
        handleSearch()
    })

    window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
    window.removeEventListener('resize', checkMobile)
    window.removeEventListener('resize', handleResize)
})

</script>
<style lang="less" scoped>
.home-content {
    height: 90%;
    transition: all 0.3s; // 添加过渡效果

    &.no-sidebar {
        width: 100%; // 移动端下占满宽度
        padding: 10px; // 添加一些内边距
    }

    .second-line {
        display: flex;
        margin-top: 16px;
        flex-wrap: wrap; // 允许在小屏幕上换行

        .button-group {
            margin-left: 20px;
        }
    }

    // 修改图表容器样式，增加响应式
    .charts-container {
        display: flex;
        margin-top: 20px;
        gap: 20px;
        flex-direction: row; // 默认横向排列

        @media screen and (max-width: 768px) {
            flex-direction: column; // 在移动端为纵向排列
            gap: 10px; // 减小间距
        }

        .chart-box {
            flex: 1;
            background: #fff;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

            @media screen and (max-width: 768px) {
                padding: 10px; // 移动端减小内边距
            }

            .chart {
                height: 400px;
                width: 100%;

                @media screen and (max-width: 768px) {
                    height: 300px; // 移动端减小图表高度
                }
            }
        }
    }
}

// 添加移动端的单适配
@media screen and (max-width: 768px) {
    .el-form {
        :deep(.el-form-item) {
            margin-right: 0;
            width: 100%;

            .el-form-item__content {
                width: 100%;
            }
        }
    }

    .second-line {
        flex-direction: column;

        .button-group {
            margin-left: 0;
            margin-top: 10px;
        }
    }
}
</style>